package com.itmaster.app.viewmodel;

import com.itmaster.LoginActivity;
import com.itmaster.domain.model.Session;
import com.itmaster.domain.model.User;
import com.itmaster.domain.model.UsersRepository;

/**
 * @author fernando.perez
 */
public class LoginViewModel {

	private LoginActivity loginActivity;
	private User user;

	public LoginViewModel(LoginActivity loginActivity) {
		this.loginActivity = loginActivity;
	}

	/**
	 */
	public void login(String username, String password) {
		try {
			loginActivity.startLogin();
			
			user = UsersRepository.getInstance().findUniqueByUsername(username);
			if (user != null && user.validatePassword(password)) {
				Session.getInstance().setUser(user);
				loginActivity.loginSuccess();
			} else {
				loginActivity.loginFail();
			}
		} catch (Exception e) {
			loginActivity.finishLogin(e);
		}
	}

	public User getUser() {
		return user;
	}
}